import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/mode/study/study_info_bean.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/format_time.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/triangle_painter.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/user_comment.dart';
import 'package:loxen/mode/mine/mine_comment_list.dart';
import 'package:loxen/viewmode/mine_user_info_viewmodel.dart';

class CommentWidget extends StatelessWidget {
  const CommentWidget({Key key}) : super(key: key);

  // 跳转到详情
  void _detailRouter(BuildContext context, String id, String type) {
    switch (type) {
      case 'idea-article':
        InspirationInfo myWorks = InspirationInfo();
        myWorks.id = int.parse(id);
        Navigator.of(context)
            .pushNamed(Routes.inspiration_detail, arguments: myWorks);
        break;
      case 'study-knowledge':
        StudyInfo entity = StudyInfo();
        entity.id = int.parse(id);
        int category = 0;
        Navigator.of(context).pushNamed(Routes.study_detail,
            arguments: {"detail": entity, "currentCategory": category});
        break;
      default:
    }
  }

  Widget _commentRow(BuildContext context, MineComment model) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(44.w),
                ),
                child: CircleAvatar(
                  radius: 44.w,
                  backgroundImage: NetworkImage(model.user.portrait),
                )),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 23.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.only(right: 4),
                              child: Text(
                                model.user.nickname,
                                style: TextStyle(
                                    color: Color(0xFF000000),
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            Text(
                              StringResources.ping_lun,
                              style: TextStyle(
                                color: Color(0xFF999999),
                                fontSize: 14,
                              ),
                            )
                          ],
                        ),
                        Text(
                          FormatTime.readTimestamp(model.addTime),
                          style: TextStyle(
                              color: Color(0xFF999999),
                              fontSize: 10,
                              fontWeight: FontWeight.w500),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 2),
                      child: Text(
                        model.content,
                        style: TextStyle(
                            fontSize: 12,
                            color: Color(0xFF000000),
                            fontWeight: FontWeight.w500),
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
        GestureDetector(
          onTap: () {
            _detailRouter(context, model.instanceId, model.contentType);
          },
          child: Stack(
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(18.w),
                margin: EdgeInsets.only(top: 14),
                color: Color(0xFFF6F6F7),
                child: Container(
                  height: 160.w,
                  child: Row(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(right: 43.w),
                        child: Image.network(
                          model.cover,
                          width: 157.w,
                          height: 157.w,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.only(bottom: 2),
                              child: Text(
                                model.title,
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                                style: TextStyle(
                                    color: Color(0xFF000000),
                                    fontSize: 28.sp,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            Text(
                              model.brief,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: TextStyle(
                                  color: Color(0xFF82868E),
                                  fontSize: 22.sp,
                                  fontWeight: FontWeight.w500),
                            ),
                            Container(
                              height: 47.w,
                              margin: EdgeInsets.only(top: 29.h),
                              child: Row(
                                children: <Widget>[
                                  Container(
                                      width: 47.w,
                                      height: 47.w,
                                      decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          image: DecorationImage(
                                              image: NetworkImage(
                                                model.infoUser.portrait,
                                              ),
                                              fit: BoxFit.cover))),
                                  Padding(
                                    padding: EdgeInsets.only(left: 7),
                                    child: Text(
                                      model.infoUser.nickname,
                                      style: TextStyle(
                                          color: Color(0xFF82868E),
                                          fontSize: 22.sp),
                                    ),
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_CommentViewModel>(create: (context) {
      String userId = Provider.of<MineUserInfoViewModel>(context, listen: false)
          .user
          .id
          .toString();
      return _CommentViewModel(userId);
    }, builder: (context, _) {
      BaseState state =
          context.select<_CommentViewModel, BaseState>((value) => value.mState);
      List<Widget> listW = [];
      listW.add(Padding(
        padding: EdgeInsets.only(left: 36.w, top: 39.h),
        child: Text(
          StringResources.ping_lun,
          style: TextStyle(
            fontSize: 32.sp,
            color: Theme.of(context).textTheme.bodyText2.color,
            fontWeight: FontWeight.bold,
          ),
        ),
      ));
      if (state == BaseState.LOADING) {
        listW.add(Container(
          height: 470.h,
          child: Center(
            child: Container(
              width: 50.w,
              height: 50.w,
              child: CircularProgressIndicator(),
            ),
          ),
        ));
      }
      if (state == BaseState.EMPTY) {
        listW.add(Container(
          padding: EdgeInsets.only(top: 40.h),
          height: 470.h,
          child: Center(
            child: Column(
              children: <Widget>[
                Image.asset(
                  "images/empty.png",
                  width: 257.w,
                  height: 240.h,
                ),
                Text(
                  "还没有任何评论",
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: Color(0X9982868E),
                  ),
                )
              ],
            ),
          ),
        ));
      }
      if (state == BaseState.FAIL) {
        listW.add(Container(
          padding: EdgeInsets.only(top: 40.h),
          height: 470.h,
          child: Center(
            child: Column(
              children: <Widget>[
                Image.asset(
                  "images/fail.png",
                  width: 257.w,
                  height: 240.h,
                ),
                Text(
                  "网络异常",
                  style: new TextStyle(
                    fontSize: 24.sp,
                    color: Color(0X9982868E),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10.h),
                  child: SizedBox(
                    width: 260.w,
                    height: 92.h,
                    child: new OutlineButton(
                      color: Colors.white,
                      textColor: Color(0XFF0CABCB),
                      child: new Text('点我'),
                      onPressed: () {
                        context.read<_CommentViewModel>().loadData();
                      },
                      borderSide: BorderSide(
                          color: Colors.blue,
                          width: 1.w,
                          style: BorderStyle.solid),
                    ),
                  ),
                )
              ],
            ),
          ),
        ));
      }
      if (state == BaseState.CONTENT) {
        return Builder(builder: (context) {
          List<Widget> listW = [];
          listW.add(Padding(
            padding: EdgeInsets.only(left: 36.w, top: 39.h),
            child: Text(
              StringResources.ping_lun,
              style: TextStyle(
                fontSize: 32.sp,
                color: Theme.of(context).textTheme.bodyText2.color,
                fontWeight: FontWeight.bold,
              ),
            ),
          ));
          bool first = true;
          var data = context
              .select<_CommentViewModel, List<MineComment>>(
                  (value) => value.data)
              .map((item) {
            if (first) {
              first = false;
              return Padding(
                padding: EdgeInsets.only(left: 36.w, top: 39.h, right: 36.w),
                child: _commentRow(context, item),
              );
            } else {
              return Padding(
                padding: EdgeInsets.only(left: 36.w, top: 80.h, right: 36.w),
                child: _commentRow(context, item),
              );
            }
          }).toList();
          listW.addAll(data);
          if (Provider.of<_CommentViewModel>(context, listen: false).isNext()) {
            listW.add(loadButton(() {
              Provider.of<_CommentViewModel>(context, listen: false).next();
            }));
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: listW,
          );
        });
      }

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: listW,
      );
    });
  }

  Widget loadButton(Function() onClick) {
    ValueNotifier<bool> _click = ValueNotifier(false);
    return ValueListenableProvider.value(
        value: _click,
        child: GestureDetector(
          onTap: () {
            if (!_click.value) {
              onClick.call();
              _click.value = true;
            }
          },
          child: Container(
            width: double.infinity,
            height: 120.h,
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
                  bool click = context.watch<bool>();
                  return click
                      ? Container(
                          width: 50.w,
                          height: 50.w,
                          child: CircularProgressIndicator(),
                        )
                      : Text(
                          '更多评论',
                          style: TextStyle(
                              fontSize: 24.sp,
                              color: Color(
                                0xFF999999,
                              )),
                        );
                },
              ),
            ),
          ),
        ));
  }
}

class _CommentViewModel extends BaseViewModel with UserCommentMixin {
  final String userId;

  MineCommentList likeList;
  List<MineComment> data;
  int pageSize = 3;
  int page = 1;

  _CommentViewModel(this.userId) {
    loadData();
  }

  void next() {
    if (isNext()) {
      page += 1;
      userComment(
              userId: userId,
              page: page.toString(),
              pageSize: pageSize.toString())
          .listen((event) {
        if (event != null) {
          likeList = event;
          data = data.take(data.length).toList();
          data.addAll(event.results);
          notifyListeners();
        }
      }, onError: (error, stack) {
        print(error);
        print(stack);
      });
    }
  }

  bool isNext() {
    return likeList != null && likeList.next.trim() != '';
  }

  void loadData() {
    userComment(userId: userId, pageSize: pageSize.toString()).doOnListen(() {
      mState = BaseState.LOADING;
      notifyListeners();
    }).listen((event) {
      if (event != null && event.results != null && event.results.length > 0) {
        likeList = event;
        data = event.results;
        mState = BaseState.CONTENT;
      } else {
        mState = BaseState.EMPTY;
      }
    }, onError: (error, stack) {
      mState = BaseState.FAIL;
      print(error);
      print(stack);
    }, onDone: () => notifyListeners());
  }
}
